package cn.yunhe.servlet;

import cn.yunhe.bean.Page;
import cn.yunhe.bean.Scenery;
import cn.yunhe.biz.SceneryService;
import cn.yunhe.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/ToMainServlet")
public class ToMainServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到当前页
        String currPage = request.getParameter("pageIndex");
        //如果当前页为空，那么就是第一页 currPage=1
        if (currPage ==null){
            currPage = "1";
        }
        int pageIndex = Integer.parseInt(currPage);
        //得到分页的List
        SceneryService sceneryService = new SceneryService();
        // 总页数
        int totalPages =PageUtil.getSceneryPage(sceneryService.getSceneryCount(),PageUtil.sceneryPageSize);
        //首页和尾页判断
        if(pageIndex<1){
            pageIndex = 1;
        }
        if (pageIndex >totalPages ){
            pageIndex = totalPages;
        }
        //根据当前页和每页条数，赋值给Page的属性
        Page page = new Page();
        page.setStartPage(PageUtil.sceneryPageSize*(pageIndex-1));

        page.setEndPage(PageUtil.sceneryPageSize);

        List<Scenery> sceneryList = sceneryService.getSceneryByPage(page);

        //将List放在request区域
        request.getSession().setAttribute("totalPages",totalPages);
        request.getSession().setAttribute("pageIndex",pageIndex);
        request.getSession().setAttribute("sceneryList",sceneryList);
        //跳转当前页面
        /*request.getRequestDispatcher("sceneryShow.jsp").forward(request,response);*/
        response.sendRedirect("sceneryShow.jsp");
    }
}
